<template>
  <x-back class="certification-page">
    <template #header>
      <label>{{ $route.meta.title }}</label>
      <div class="title-btn">
        <el-button @click="handleCancel"> {{ $t('common.cancel') }} </el-button>
        <el-button @click="handleSubmitCom"> {{ $t('common.save') }} </el-button>
        <el-button v-if="activeStep >= 1" type="primary" @click="handleSubmit('pre')">
          {{ $t('common.preStep') }}
        </el-button>
        <el-button type="primary" @click="handleSubmit(activeStep === 7 ? 'submit' : 'next')" :loading="loading">
          {{ activeStep === 7 ? $t('common.submit') : $t('common.nextStep') }}
        </el-button>
      </div>
    </template>
    <el-alert
      :title="auditInfo?.auditState === 3 ? '审核驳回' : '请完善资料后提交审核'"
      :type="auditInfo?.auditState === 3 ? 'error' : 'warning'"
      show-icon
    >
      <template #description>
        <div class="tips-contant" v-if="auditInfo?.auditState === 3">
          <div class="tips-text"> 驳回理由：{{ auditInfo.auditRemark }} </div>
          <span>驳回时间:{{ auditInfo.updateTime }}</span>
        </div>
      </template>
    </el-alert>
    <div class="main-panel">
      <certification-step ref="stepComponent" :active-step="activeStep" :step-options="stepList" />
      <div class="form-components">
        <div class="panl-title">
          <span>{{ stepList[activeStep].label || '' }}</span>
        </div>
        <transition name="fade-form">
          <enterprise-form
            v-if="activeStep === 0"
            ref="baseComponent"
            :dict-options="dictOptions"
            :supplier-id="supplierId"
            :key="0"
          />
          <!-- 法定代表人信息-->
          <representative-form
            v-if="activeStep === 1"
            ref="representComponent"
            :dict-options="dictOptions"
            :supplier-id="supplierId"
            :key="1"
          />
          <!-- 企业负责人-->
          <responsible-person-form
            v-if="activeStep === 2"
            ref="responsibleComponent"
            :dict-options="dictOptions"
            :supplier-id="supplierId"
            :key="2"
          />
          <!-- 股本结构-->
          <capital-structure-form
            v-if="activeStep === 3"
            ref="capitalComponent"
            :dict-options="dictOptions"
            :supplier-id="supplierId"
            :key="3"
          />
          <!-- 发票信息-->
          <invoice-form
            v-if="activeStep === 4"
            ref="invoiceComponent"
            :dict-options="dictOptions"
            :supplier-id="supplierId"
            :key="4"
          />
          <!-- 银行信息-->
          <bank-form
            v-if="activeStep === 5"
            ref="bankComponent"
            :dict-options="dictOptions"
            :supplier-id="supplierId"
            :key="5"
          />
          <!-- 人员信息-->
          <person-form
            v-if="activeStep === 6"
            ref="personComponent"
            :dict-options="dictOptions"
            :supplier-id="supplierId"
          />
          <!-- 准入信息 -->
          <access-form
            v-if="activeStep === 7"
            ref="accessComponent"
            :dict-options="dictOptions"
            :supplier-id="supplierId"
            :key="7"
          />
        </transition>
      </div>
    </div>
  </x-back>
</template>
<script>
  import { QueryDictMixin, throttle } from '@package/utils'
  import { mapState, mapActions } from 'pinia'
  import CertificationStep from './certificationStep.vue'
  import BankForm from './bankForm.vue'
  import CapitalStructureForm from './capitalStructureForm.vue'
  import EnterpriseForm from './enterpriseForm.vue'
  import InvoiceForm from './invoiceForm.vue'
  import RepresentativeForm from './representativeForm.vue'
  import ResponsiblePersonForm from './responsiblePersonForm.vue'
  import PersonForm from './personForm.vue'
  import AccessForm from './accessForm.vue'

  import { stepList } from '../config/recordConfig'

  import {
    apiMaterialTypeTree,
    apiSupplierRankList,
    apiGetSupplierArchives,
    apiPostGetServiceType,
    apiPostAreaTree
  } from '../api/record'

  import { EnumApiCode } from '../../../../../../globalEnum.js'

  import { pinias } from '@/common/pinia'

  const { recordStore } = pinias
  export default {
    name: 'RecordInfo',
    components: {
      CertificationStep,
      BankForm,
      CapitalStructureForm,
      EnterpriseForm,
      InvoiceForm,
      RepresentativeForm,
      ResponsiblePersonForm,
      PersonForm,
      AccessForm
    },
    mixins: [QueryDictMixin],
    inject: ['closePages'],
    computed: {
      ...mapState(recordStore, ['supplierId'])
    },
    data() {
      return {
        stepList,
        activeStep: 0,
        loading: false,
        dictKeys: ['system.whether', 'system.state'],
        srmDictKeys: [
          'bank_category',
          'shareholder_type',
          'certificate_type',
          'srm_supplier_info.qualification_category',
          'srm_supplier_info.economic_type',
          'srm_supplier_info.enterprise_type',
          'currency',
          'srm_supplier_info.enterprise_attribute',
          'srm_supplier_info.nature',
          'srm_supplier_info.source',
          'srm_supplier_info.audit_state'
          // ''
        ],
        auditInfo: {
          auditState: '',
          supplierState: ''
        }
      }
    },
    created() {
      const data = this.$route.query
      this.auditInfo = data
      this.setSupplierId(data?.id ?? '')

      Promise.all([
        // 基础字典
        this.initDictConfig(),
        // 准入类型和等级
        this.initSupplierDict(),
        // 所属国家
        this.initCountryOptions(),
        // 主供产品类型
        this.initServiceTypeOptions()
      ])
    },
    methods: {
      ...mapActions(recordStore, ['setSupplierId']),
      async initSupplierDict() {
        try {
          const data = await Promise.all([apiMaterialTypeTree(), apiSupplierRankList()])
          const { data: treeData } = data[0]
          const { data: levalData } = data[1]
          this.$set(this.dictOptions, 'access_type', treeData)
          this.$set(this.dictOptions, 'access_level', levalData)
        } catch {
          console.error('供应商等级/行业分类获取失败')
        }
      },
      async initCountryOptions() {
        const { data } = await apiPostAreaTree({ areaLevel: 0, state: 1 })
        this.$set(this.dictOptions, 'country', data)
      },
      async initServiceTypeOptions() {
        const { data } = await apiPostGetServiceType({ state: 1 })
        this.$set(this.dictOptions, 'main_serve_type', data)
      },
      /**
       * 下一步操作
       * @param param  subType:submit:提交  next:下一步
       * @return {*|Promise}
       */
      handleSubmit: throttle(function (subType) {
        if (subType === 'submit') {
          this.handleCompleteInfo()
        } else if (subType === 'next') {
          const componentName = this.stepList[this.activeStep].component
          this.$refs[componentName]
            .onSumit()
            .then(() => {
              this.activeStep++
            })
            .catch((error) => {
              this.$message.error(error)
            })
        } else {
          this.activeStep--
        }
      }, 1000),
      // 提交审核
      handleCompleteInfo() {
        // 先保存在提交
        const componentName = this.stepList[this.activeStep].component
        this.$refs[componentName].onSumit().then(() => {
          apiGetSupplierArchives(this.supplierId)
            .then(({ code }) => {
              if (code === EnumApiCode.Success) {
                this.$message.success('已成功提交！')
                this.$router.go(-1)
                this.closePages()
                // this.getDetail()
              }
            })
            .catch(() => {})
        })
      },
      // 保存
      handleSubmitCom() {
        const componentName = this.stepList[this.activeStep].component
        this.$refs[componentName].onSumit(false).then(() => {
          this.$message.success('已成功保存！')
        })
      },
      handleCancel() {
        this.$confirm('确定放弃当前操作返回吗?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.$router.go(-1)
          this.closePages()
        })
      }
    }
  }
</script>
<style lang="scss">
  @import '../style/index.scss';
  /* fade-transform */
  .fade-form-enter-active {
    transition: all 0.6s ease-in 0.2s;
    opacity: 1;
    transform: translateX(0px);
  }

  .fade-form-leave-active {
    transition: all 0.2s ease-out;
    opacity: 0;
    transform: translateX(30px);
  }

  .fade-form-enter {
    opacity: 0;
    transform: translateX(-30px);
  }

  .fade-form-leave-to {
    opacity: 0;
    transform: translateX(0);
  }
</style>
